package demoflink.window;

import demoflink.entity.WaterSensor;
import demoflink.function.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class WindowMixApi {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        KafkaSource<String> kafkaSource = KafkaSource.<String>builder()
                .setBootstrapServers("node1:9092,node2:9092,node3:9092")
                .setGroupId("local")
                .setTopics("first")
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .setStartingOffsets(OffsetsInitializer.latest())
                .build();
        SingleOutputStreamOperator<WaterSensor> source = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafkaSource").map(new WaterSensorMapFunction());

        KeyedStream<WaterSensor, String> keyedStream = source.keyBy(x -> x.getId());
        WindowedStream<WaterSensor, String, TimeWindow> window = keyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(10)));
        window.aggregate(new MyAgg(),new MyProcess()).print();


        env.execute();

    }

    public static class MyAgg implements AggregateFunction<WaterSensor, Integer, String>{

        /**
         * 初始化累加器中的某些值
         * @return
         */
        @Override
        public Integer createAccumulator() {
            System.out.println("创建累加器");
            return 0;
        }

        /**
         * 聚合逻辑
         * @param waterSensor
         * @param integer
         * @return
         */
        @Override
        public Integer add(WaterSensor waterSensor, Integer integer) {
            System.out.println("调用累加器");
            return integer + waterSensor.getVc();
        }

        /**
         * 窗口结束时触发获取结果
         * @param integer
         * @return
         */
        @Override
        public String getResult(Integer integer) {
            System.out.println("获取结果");
            return integer.toString();
        }

        /**
         * 一般不会用到 只有会话窗口会用到
         * @param integer
         * @param acc1
         * @return
         */
        @Override
        public Integer merge(Integer integer, Integer acc1) {

            System.out.println("调用merge函数");
            return null;
        }
    }

    public static class MyProcess extends ProcessWindowFunction<String, String, String, TimeWindow>{



        @Override
        public void process(String s, Context context, Iterable<String> iterable, Collector<String> collector) throws Exception {
            long start = context.window().getStart();
            long end = context.window().getEnd();
            String windowStart = DateFormatUtils.format(start, "yyyy-MM-dd HH:mm:ss");
            String windowEnd = DateFormatUtils.format(end, "yyyy-MM-dd HH:mm:ss");
            long count = iterable.spliterator().estimateSize();
            collector.collect("key="+s+"的窗口["+windowStart+","+windowEnd+"]包含 "+count+" 条数据=====>"+iterable.toString());
        }
    }
}
